package com.madding.shared.net.httpclient;

import org.apache.commons.httpclient.DefaultMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;

@SuppressWarnings("deprecation")
public class IrecomUtil {

    private final static HttpClient client              = new HttpClient(new MultiThreadedHttpConnectionManager());
    private static final String     PARAM_NAME_MEMBERID = "memberids";
    private static final String     PARAM_NAME_OFFERID  = "offerids";

    private static final String     PARAM_NAME_UID      = "uid";
    private static final String     PARAM_NAME_PAGEID   = "pageid";
    private static final String     PARAM_NAME_RECID    = "recid";
    private static final String     PARAM_VALUE_RECID   = "1179";
    private static final String     PARAM_VALUE_PAGEID  = "not-from-browser";

    public static String loadIrecomInfo(String currentLoginId, String memberId, long offerId) {
        GetMethod getMethod = new GetMethod("http://res.china.alibaba.com/fly/irecom.do");
        initQueryString(getMethod, currentLoginId, memberId, offerId);

        try {
			DefaultMethodRetryHandler retryHandler = new DefaultMethodRetryHandler();
            retryHandler.setRetryCount(0);
            getMethod.setMethodRetryHandler(retryHandler);
            client.setConnectionTimeout(100);
            client.setTimeout(100);
            int statusCode = client.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                String result = getMethod.getResponseBodyAsString();
                return result;
            }
        } catch (Exception e) {
        } finally {
            getMethod.releaseConnection();
        }
        return null;
    }

    private static void initQueryString(HttpMethodBase method, String currentLoginId, String memberId, long offerId) {
        if (memberId == null || offerId == 0) {
            throw new IllegalArgumentException("memberId and offerId cannot be null or an empty string");
        }
        if (currentLoginId == null) {
            currentLoginId = "-1";
        }
        NameValuePair[] params = new NameValuePair[5];
        params[0] = new NameValuePair(PARAM_NAME_MEMBERID, memberId);
        params[1] = new NameValuePair(PARAM_NAME_OFFERID, String.valueOf(offerId));
        params[2] = new NameValuePair(PARAM_NAME_PAGEID, PARAM_VALUE_PAGEID);
        params[3] = new NameValuePair(PARAM_NAME_RECID, PARAM_VALUE_RECID);
        params[4] = new NameValuePair(PARAM_NAME_UID, currentLoginId);
        method.setQueryString(params);
    }

}
